package com.mimc.framework.core;
import com.alibaba.fastjson.JSON;
import com.jfinal.handler.Handler;
import com.mimc.common.constant.EventConstants;
import com.mimc.common.constant.WebConstants;
import com.mimc.common.utils.ip.IpUtils;
import com.mimc.core.model.SysAdmin;
import com.mimc.core.model.SysOptLog;
import io.jboot.Jboot;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Slf4j
public class RequestHandler extends Handler {
    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        log.info("开始请求");
        long start=new Date().getTime();
        //request.setAttribute(WebConstants.REQUEST_ID, IdUtil.randomUUID());
        RequestContextHolder.set(request);
        next.handle(target, request, response, isHandled);
        long end=new Date().getTime();
        if(target.startsWith("/admin")){
            SysAdmin sysAdmin= (SysAdmin) request.getAttribute(WebConstants.REQUEST_ADMIN);
            if(sysAdmin!=null&&!target.toLowerCase().contains("upload")){
                long time=end-start;
                SysOptLog sysOptLog=new SysOptLog();
                sysOptLog.setAdminId(sysAdmin.getId());
                sysOptLog.setMethod(request.getMethod());
                sysOptLog.setUrl(target);
                sysOptLog.setTime(time);
                sysOptLog.setContent(JSON.toJSONString(request.getParameterMap()));
                sysOptLog.setIp(IpUtils.getIpAddr(request));
                sysOptLog.setCreateTime(new Date());
                Jboot.sendEvent(EventConstants.OPTLOGEVENT,JSON.toJSONString(sysOptLog));
            }

        }
        log.info("结束请求");

        RequestContextHolder.remove();
    }
}
